<template>
  <div id="mapPage">
    <HeadNav type="inquire" ref="head" :show="0"></HeadNav>
    <div class="map-head">
      <div>
        <span class="logo-font">博道出版数据实验室</span>
        <span style="margin-left: 10px">定位周边分析</span>
      </div>
      <div>
        <span class="map-head-icon">
          <svg
            class="icon"
            aria-hidden="true"
            @click.stop="$router.push({ name: 'usersuggesstion' })"
          >
            <use xlink:href="#icon-kefu" />
          </svg>
        </span>
        <span class="map-head-icon">
          <svg
            class="icon"
            aria-hidden="true"
            @click.stop="$router.push({ name: 'helpindex' })"
          >
            <use xlink:href="#icon-question" />
          </svg>
        </span>
        <span class="map-head-icon">
          <svg
            class="icon"
            aria-hidden="true"
            @click.stop="$router.push({ name: 'usernotice' })"
          >
            <use xlink:href="#icon-notice" />
          </svg>
        </span>
      </div>
    </div>
    <div class="map-container">
      <div class="map-left">
        <div class="map-left-title">检索设置</div>
        <div class="map-left-search">
          <div class="map-left-search-lable">定位坐标</div>
          <div style="margin-top: 10px">
            <div class="map-search-list bg" @click="showSearch = true">
              <span class="map-search-icon"
                ><svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-daohang" /></svg
              ></span>
              <div>
                <div class="map-search-list-title">{{ cureentInfo.title }}</div>
                <div class="map-search-list-text">{{ cureentInfo.detail }}</div>
              </div>
            </div>
          </div>
          <div class="map-left-search-lable">检索半径</div>
          <div>
            <a-row type="flex" align="middle">
              <a-col :span="6">
                <span class="main-font">{{ searchRadius }}公里</span>
              </a-col>
              <a-col :span="18">
                <a-slider
                  v-model="searchRadius"
                  :min="0.5"
                  :max="5"
                  :step="0.5"
                />
              </a-col>
            </a-row>
          </div>
          <!-- <div class="map-left-search-lable">用户分群</div>
          <div style="margin-top: 10px">
            <a-select default-value="1" style="width: 100%">
              <a-select-option value="1"> 全部用户 </a-select-option>
              <a-select-option value="2"> 新用户 </a-select-option>
              <a-select-option value="3"> 高价值用户 </a-select-option>
            </a-select>
          </div> -->
        </div>
        <!-- 搜索 -->
        <div class="map-search-contaner" v-if="showSearch">
          <div class="map-search-head">
            <a-icon type="left" style="cursor: pointer" @click="closeSearch" />
            <a-input
              placeholder="搜索地点"
              v-model="inputVal"
              style="margin-left: 10px"
            />
          </div>
          <div class="map-search-content">
            <div
              class="map-search-list"
              v-for="(item, index) in resultList"
              :key="index"
              @click="selectRegion(item)"
            >
              <span class="map-search-icon"
                ><svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-daohang" /></svg
              ></span>
              <div>
                <div class="map-search-list-title">{{ item.title }}</div>
                <div class="map-search-list-text">
                  {{ item.address }}
                  <!-- {{ item.province?item.province:'' + item.city?item.city:'' + item.title }} -->
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="map-mid">
        <baidu-map
          id="baidu-map"
          ak="vjFV8LmCgfnmxHACZeeOHVZZZeQEcMee"
          scroll-wheel-zoom
          :mapClick="false"
          :center="mapCenter"
          :zoom="15"
          @ready="initMap"
        >
          <bm-view style="width: 100%; height: 100%"></bm-view>
          <bm-panorama></bm-panorama>
          <bm-navigation anchor="BMAP_ANCHOR_BOTTOM_RIGHT"></bm-navigation>
          <!-- <bm-geolocation
            anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
            :showAddressBar="true"
            :autoLocation="true"
            @locationSuccess="positionSuccess"
            @locationError="failed"
          ></bm-geolocation> -->
          <bm-local-search
            :keyword="inputVal"
            :panel="false"
            :auto-viewport="false"
            @searchcomplete="mapSearch"
          ></bm-local-search>
          <bm-circle
            :center="cureentInfo.point"
            :radius="searchRadius * 1000"
            stroke-color="blue"
            :stroke-opacity="0.5"
            :stroke-weight="2"
            :massClear="false"
          ></bm-circle>
        </baidu-map>
      </div>
      <div class="map-right">
        <div>
          <a-button type="primary" block v-if="countLoading" disabled
            >查询用户数据</a-button
          >
          <a-button v-else type="primary" block @click="searchUser"
            >查询用户数据</a-button
          >
        </div>
        <div style="margin-top: 20px; margin-bottom: 10px">周边读者人数</div>
        <div v-if="countLoading">
          <a-spin :indicator="indicator" />
        </div>
        <div v-else>
          <span class="user-num">{{ readerNum }}人</span>
        </div>
        <!-- <div style="margin-top: 35px; margin-bottom: 10px">自然性别分布</div>
        <div id="sex-map"></div>
        <div style="margin-top: 35px; margin-bottom: 10px">购物性别分布</div>
        <div id="shopping-sex"></div>
        <div style="margin-top: 35px; margin-bottom: 10px">偏好关键字</div>
        <div id="shopping-sex"></div> -->
      </div>
    </div>
    <Loading ref="load" :show="1" :isLoading="isLoading"></Loading>
  </div>
</template>
<style lang="scss" scoped>
#mapPage {
  width: 100%;
  height: 100%;
  & .map-head {
    background-color: $fontColor1;
    height: 52px;
    @include displayFlex(flex, space-between, center);
    padding: 0 20px;
    color: $clf;
    & .map-head-icon {
      margin-left: 25px;
      cursor: pointer;
      font-size: $fontSize + 2;
    }
  }
  & .map-container {
    width: 100%;
    height: calc(100% - 52px);
    position: relative;
    & .main-font {
      color: $fontColor1;
    }
    & .map-left {
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      width: 300px;
      background-color: $clf;
      & .map-left-title {
        line-height: 52px;
        color: $fontColor1;
        padding: 0 20px;
        border-bottom: 1px solid $themeColor5;
      }
      & .map-left-search {
        padding: 0 20px;
        font-size: $fontSize - 2;
        & .map-left-search-lable {
          margin-top: 30px;
        }
      }
      & .map-search-list {
        @include displayFlex(flex, null, null);
        cursor: pointer;
        padding: 10px;
        &:hover,
        &.bg {
          background-color: $themeColor5;
        }
        & .map-search-icon {
          margin-right: 5px;
          font-size: $fontSize + 2;
          color: $fontColor1;
        }
        & .map-search-list-title {
          font-size: $fontSize;
          color: $fontColor1;
        }
        & .map-search-list-text {
          font-size: $fontSize - 2;
          margin-bottom: 5px;
        }
      }
      & .map-search-contaner {
        position: absolute;
        top: 53px;
        left: 0;
        bottom: 0;
        right: 0;
        width: 100%;
        background-color: $clf;
        z-index: 10;
        padding: 20px;
        & .map-search-head {
          @include displayFlex(flex, null, center);
          margin-bottom: 10px;
        }
        & .map-search-content {
          position: absolute;
          top: 62px;
          left: 20px;
          bottom: 20px;
          right: 20px;
          width: calc(100% - 40px);
          overflow-y: scroll;
        }
      }
    }
    & .map-right {
      position: absolute;
      right: 0;
      top: 0;
      bottom: 0;
      width: 300px;
      background-color: $clf;
      padding: 20px;
      font-size: $fontSize - 2;
      & .user-num {
        color: $fontColor1;
        font-weight: bold;
      }
    }
    & .map-mid {
      position: absolute;
      left: 300px;
      top: 0;
      bottom: 0;
      right: 300px;
    }
  }
  #baidu-map {
    overflow: hidden;
    width: 100%;
    height: 100%;
    margin: 0;
  }
}
/deep/ .anchorBL {
  display: none;
}
</style>
<script>
import { COMMON_REGION } from "../../../apis/common.js";
import { QUERY_LOCATION_NEAR } from "../../../apis/inquire.js";
import BaiduMap from "vue-baidu-map/components/map/Map.vue";
import BmView from "vue-baidu-map/components/map/MapView.vue";
import BmNavigation from "vue-baidu-map/components/controls/Navigation";
import BmGeolocation from "vue-baidu-map/components/controls/Geolocation";
import BmPanorama from "vue-baidu-map/components/controls/Panorama";
import BmLocalSearch from "vue-baidu-map/components/search/LocalSearch";
import BmCircle from "vue-baidu-map/components/overlays/Circle";
export default {
  components: {
    BaiduMap,
    BmView,
    BmNavigation,
    BmGeolocation,
    BmLocalSearch,
    BmPanorama,
    BmCircle,
  },
  data() {
    return {
      pagePower: true,
      mapCenter: null,
      BMap: null,
      map: null,
      searchRadius: 0.5,
      inputVal: "",
      resultList: [],
      cureentInfo: {
        point: {
          lng: "",
          lat: "",
        },
        title: "",
        detail: "",
      },
      province: "",
      city: "",
      provinceCode: 0,
      cityCode: 0,
      showSearch: false,
      isLoading: true,
      countLoading: false,
      regionList: [],
      readerNum: 0,
      websocket: null,
      indicator: <a-icon type="loading" spin />,
      pointList: [],
      canWebsocket: false,
    };
  },
  mounted() {
    this.getRegion();
    // let wsServer = "ws://198.210.10.208:9510";
    let wsServer = "ws://101.37.66.93:9510";
    let _this = this;
    let websocket = new WebSocket(wsServer);
    this.websocket = websocket;
    // websocket通信
    websocket.onopen = function (evt) {
      _this.canWebsocket = true;
      console.log("服务器连接成功", evt);
    };
    websocket.onclose = function (evt) {
      _this.countLoading = false;
      _this.canWebsocket = false;
      console.log("服务器连接断开");
    };
    websocket.onmessage = function (evt) {
      let _data = JSON.parse(evt.data);
      if (_data.return.code == 0) {
        _this.readerNum = _data.return.data.total_count;
        _this.countLoading = false;
      } else {
        _this.countLoading = false;
        _this.$refs.head.globalTip(1, _data.return.message, _data.return.code);
      }
      console.log("服务器通信", _data);
    };
    websocket.onerror = function (evt, e) {
      _this.countLoading = false;
      _this.canWebsocket = false;
      console.log("服务器连接失败", evt);
    };
  },
  methods: {
    // 查询数据
    async getData() {
      var tStamp = this.$getTimeStamp();
      let data = {
        lng: this.cureentInfo.point.lng.toString(),
        lat: this.cureentInfo.point.lat.toString(),
        distance: this.searchRadius * 1000,
        province_code: this.provinceCode,
        city_code: this.cityCode,
        timestamp: tStamp,
      };
      data.sign = this.$getSign(data);
      // 发送websocket
      if (this.canWebsocket) {
        let wsData = {
          request_url: "/query/location/count",
          cookie: {
            pd_token: localStorage.getItem("token")
              ? localStorage.getItem("token")
              : "",
          },
          parameter: data,
        };
        this.websocket.send(JSON.stringify(wsData));
      }
      let res = await QUERY_LOCATION_NEAR(data);
      if (res.code == 0) {
        this.pagePower = true;
        this.map.clearOverlays();
        this.pointList = [];
        if (res.data.list) {
          this.pointList = res.data.list;
          res.data.list.map((val) => {
            let mk = new this.BMap.Marker(val);
            this.map.addOverlay(mk);
          });
        }
        this.$nextTick(() => {
          this.isLoading = false;
        });
      } else {
        this.isLoading = false;
        if (res.code == 1009) {
          this.pagePower = false;
        } else {
          this.$refs.head.globalTip(1, res.message, res.code);
        }
      }
    },
    // 获取地区分类列表
    async getRegion() {
      var tStamp = this.$getTimeStamp();
      let data = {
        timestamp: tStamp,
      };
      data.sign = this.$getSign(data);
      let res = await COMMON_REGION(data);
      if (res.code == 0) {
        this.regionList = [];
        this.regionList = res.data;
        this.$nextTick(() => {
          this.isLoading = false;
        });
      } else {
        this.isLoading = false;
        this.$refs.head.globalTip(1, res.message, res.code);
      }
    },
    // 地图初始化
    initMap({ BMap, map }) {
      let _this = this;
      this.BMap = BMap;
      this.map = map;
      let geolocation = new BMap.Geolocation();
      let gc = new BMap.Geocoder(); //创建地理编码器
      // 开启SDK辅助定位
      geolocation.enableSDKLocation();
      geolocation.getCurrentPosition(function (r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
          let mk = new BMap.Marker(r.point);
          map.addOverlay(mk);
          _this.mapCenter = { lng: r.point.lng, lat: r.point.lat }; // 设置center属性值
          //   _this.mapCenter = {
          //     lat: 30.34397726551,
          //     lng: 120.10350056256,
          //   }
          let pt = r.point;
          map.panTo(pt); //移动地图中心点
          gc.getLocation(pt, function (rs) {
            _this.cureentInfo.point = pt;
            _this.cureentInfo.title = rs.business;
            _this.cureentInfo.detail = rs.address;
            _this.province = rs.addressComponents.province;
            _this.city = rs.addressComponents.city;
          });
        } else {
          _this.$refs.head.globalTip(1, "定位失败！", 0);
        }
      });
    },
    positionSuccess(point, AddressComponent, marker) {},
    failed(StatusCode) {
      this.$refs.head.globalTip(1, "定位失败！", 0);
    },
    // 解析省市code
    parseCode() {
      let pcode, ccode;
      this.regionList.map((val) => {
        if (this.province && this.province.indexOf(val.name) > -1) {
          pcode = val.code;
          if (this.city) {
            val.children.map((v) => {
              if (this.city.indexOf(v.name) > -1) {
                ccode = v.code;
              }
            });
          }
        }
      });
      this.provinceCode = pcode;
      this.cityCode = ccode;
      this.getData();
    },
    // 位置搜索
    mapSearch(e) {
      console.log(6666,e);
      if (e) {
        this.resultList = e.Ir;
        this.$nextTick(() => {
          this.map.clearOverlays();
          let mk = new this.BMap.Marker(this.cureentInfo.point);
          this.map.addOverlay(mk);
          this.pointList.map((val) => {
            let mk = new this.BMap.Marker(val);
            this.map.addOverlay(mk);
          });
        });
      } else {
        this.resultList = [];
      }
    },
    closeSearch() {
      this.showSearch = false;
    },
    // 选择地区
    selectRegion(item) {
      this.showSearch = false;
      this.cureentInfo.point = item.point;
      this.cureentInfo.title = item.title;
      this.cureentInfo.detail = item.address;
      this.map.clearOverlays();
      let mk = new this.BMap.Marker(item.point);
      this.readerNum = 0;
      this.map.addOverlay(mk);
      this.map.panTo(item.point); //移动地图中心点
    },
    // 查询
    searchUser() {
      this.isLoading = true;
      if (this.canWebsocket) {
        this.countLoading = true;
      }
      let gc = new this.BMap.Geocoder(),
        pt = this.cureentInfo.point,
        _this = this;
      gc.getLocation(pt, function (rs) {
        _this.province = rs.addressComponents.province;
        _this.city = rs.addressComponents.city;
        _this.parseCode();
      });
    },
  },
};
</script>